﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace FusionDotNet
{
    /// <summary>
    /// Select rows from a Google Fusion Table.
    /// </summary>
    public class SelectCommand : GetCommand<SelectResult>
    {
        private string m_CommandText;

        /// <summary>
        /// Default Constructor.
        /// </summary>
        /// <param name="query">query used to define the result set.</param>
        public SelectCommand(string query)
        {
            if (String.IsNullOrEmpty(query))
            {
                throw ExceptionBuilder.BuildException<ArgumentException>("Query may not be null or empty.");
            }
            m_CommandText = query;
        }

        /// <summary>
        /// Sets the Query string for the Command.
        /// </summary>
        /// <returns>String to use as the Query string.</returns>
        protected override string GetCommandQueryString()
        {
            return m_CommandText;
        }

        internal override SelectResult CreateResult(StreamReader reader)
        {
            using (DataTable resultTable = new DataTable())
            {
                string[] headers = reader.ReadLine().Split(',');
                TableBuilder.AddColumnHeaders(headers, resultTable);

                while (!reader.EndOfStream)
                {
                    string[] columns = reader.ReadLine().Split(',');
                    resultTable.Rows.Add(columns);
                }

                var result = new SelectResult(resultTable);
                return result;
            }
        }

    }
}
